package com.wx.house.terminal.api.client.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.house.common.assembly.alyidcard.IDCardResult;
import com.wx.house.common.assembly.alyidcard.IDCardUtil;
import com.wx.house.common.assembly.alysms.MessageUtil;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.common.util.StringUtil;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.dto.tenant.TenantCertificationUpDto;
import com.wx.house.core.pojo.dto.tenant.TenantResetPasswordUpDto;
import com.wx.house.core.pojo.dto.tenant.TenantSignInDto;
import com.wx.house.core.pojo.po.TUser;
import com.wx.house.core.pojo.state.LogicalDeleteEnum;
import com.wx.house.core.pojo.state.TenantSignTypeEnum;
import com.wx.house.core.pojo.state.TenantStateEnum;
import com.wx.house.core.pojo.vo.TUserVo;
import com.wx.house.terminal.api.client.service.TenantSignService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author ：罗棋
 * @Email ：58428467@qq.com
 * @date ：Created in 2019/11/18 下午 03:56
 * @description：
 * @version: ：V
 */
@RestController
@RequestMapping("tenant/sign/")
@Slf4j
@RequiredArgsConstructor
@Api(tags = "登陆系统")
@Validated
public class TenantSignController extends BaseController {
    private final TenantSignService tenantSignService;

    private static String TENANT_TERMINAL_SIGN = "WX:HOUSING:TERMINAL_SIGN:%s";

    @ApiOperation("登陆")
    @PostMapping("signIn")
    public Result signIn(@RequestBody @Validated TenantSignInDto tenantSignInDto, HttpServletResponse response) {
        TUserVo tUser = tenantSignService.selectByPhoneNumber(tenantSignInDto.getPhone());
        TUser registerUser = null;

        //如果是注册则一定不会校验密码,只会验证 密码
        if (tenantSignInDto.getSignType().equals(TenantSignTypeEnum.PASSWORD.type)) {//验证密码
            if (tUser == null) {
                throw new BusinessException("还未注册，请先注册");
            }

            if (StringUtil.isEmpty(tUser.getPassword())) {
                throw new BusinessException("还未设置密码");
            }

            if (!this.comparePassword(tenantSignInDto.getCode(), tUser.getPassword(), Integer.parseInt(tUser.getSafekey()))) {
                throw new BusinessException("登陆失败，密码错误");
            }

        } else if (tenantSignInDto.getSignType().equals(TenantSignTypeEnum.VALID_CODE.type)) {//验证 验证码
            String validCode = this.redisUtil().get(String.format(MessageUtil.SEND_CODE, tenantSignInDto.getPhone()));
            if (validCode == null) throw new BusinessException("还未发送验证码");
            if (!validCode.equals(tenantSignInDto.getCode())) {
                throw new BusinessException("验证码错误");
            }

        }
        if (tUser == null) {
            registerUser = new TUser();
            //用户不存在，注册
            registerUser.setId(IDUtils.createUUId());
            registerUser.setState(TenantStateEnum.NORMAL.state);
            registerUser.setSafekey(IDUtils.getSafeKey());
            registerUser.setDelType(LogicalDeleteEnum.NORMAL.state);
            registerUser.setPhoneNumber(tenantSignInDto.getPhone());
            registerUser.setPassword("");
            tenantSignService.insertSelective(registerUser);
            tUser = new TUserVo();
            tUser.setId(registerUser.getId());
            tUser.setName("");
            tUser.setHasPassword(false);
            tUser.setPhoneNumber(registerUser.getPhoneNumber());
            tUser.setPassword("");
        } else {
            //不是新注册用户才校验状态
            if (tUser.getState().equals(TenantStateEnum.FREEZE.state)) {
                throw new BusinessException(TenantStateEnum.FREEZE.description);
            }
        }

        Map<String, String> paramList = new HashMap<>();
        paramList.put("id", tUser.getId());
        paramList.put("phone", tUser.getPhoneNumber());
        JwtUtils jwtUtils = JwtUtils
                .builder()
                .username(tUser.getName())
                .paramList(paramList)
                .build();

        this.redisUtil().set(String.format(TENANT_TERMINAL_SIGN, tUser.getPhoneNumber()), jwtUtils.token());
        response.setHeader("authorization", jwtUtils.token());

        //不存在注册信息，是普通登陆
        if (registerUser == null) return Result.success("success", tUser);
        //注册成功
        return Result.success("注册成功", tUser);


    }


    @ApiOperation("重置密码-初次设置密码")
    @PostMapping("resetPassword")
    public Result restPassword(@RequestBody @Validated TenantResetPasswordUpDto tenantResetPasswordUpDto) {
        String validCode = this.redisUtil().get(String.format(MessageUtil.SEND_CODE, tenantResetPasswordUpDto.getPhone()));
        if (validCode == null) throw new BusinessException("还未发送验证码");
        if (!validCode.equals(tenantResetPasswordUpDto.getValidCode())) {
            throw new BusinessException("验证码错误");
        }

        if (!tenantResetPasswordUpDto.getCode1().equals(tenantResetPasswordUpDto.getCode2())) {
            throw new BusinessException("两次输入的密码不一致");
        }
        Integer safeKey = IDUtils.getIntegerSafeKey();
        TUserVo signUser = tenantSignService.selectByPhoneNumber(tenantResetPasswordUpDto.getPhone());
        String password = this.createPassword(tenantResetPasswordUpDto.getCode1(), safeKey);
        if (signUser == null) {
            throw new BusinessException("此手机号还未注册，请先去注册");
        }
        if (password.equals(signUser.getPassword()) || signUser.getPassword() == null) {
            throw new BusinessException("此密码和上次设置密码相同，请重新输入");
        }
        if (tenantSignService.updatePassword(signUser.getId(), password, safeKey) != 1) {
            throw new BusinessException("设置密码错误");
        }
        return Result.success();
    }

    @ApiOperation("退出登陆")
    @PostMapping("logout")
    public Result logout() {
        String userPhone = this.getUserPhone();
        try {
            redisUtil().delete(String.format(TENANT_TERMINAL_SIGN, userPhone));
        } catch (Exception ignored) {
        }
        return Result.success();
    }

}
